package com.shwread.android.qysw.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.services.core.PoiItem;
import com.ciko.code.http.BaseResponse;
import com.ciko.code.http.HttpClient;
import com.ciko.code.http.HttpResponseListener;
import com.ciko.code.http.Req.AddWorkOutsideInfo;
import com.ciko.code.logic.bean.AddressBookInfo;
import com.ciko.code.type.EmployeeEnum;
import com.ciko.code.utils.DateUtil;
import com.ciko.code.utils.ScreenUtil;
import com.google.gson.Gson;
import com.mywork.activity.ApproverActivity;
import com.shwread.android.qysw.bean.MessageEvent;
import com.shwread.android.qysw10000182.R;
import com.shwread.android.ui.widget.CircleImageView;
import com.squareup.picasso.Picasso;
import com.ui.pickerview.view.TimePickerView;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;
import logic.util.Util;
/*
*
* 因公外出申请页面
*
* */

public class BusinessTripActivity extends AppCompatActivity implements
        View.OnClickListener,
        HttpResponseListener, TimePickerView.OnTimeSelectListener {

    private TextView txt_date;
    private TextView end_time_out;
    private TextView txt_record;
    private Button btn_ok;
    private LinearLayout lin_mapview, ll;
    private TextView tvJob;
    private TextView tvName;
    private EditText et_reason;
    private EditText et_name;
    private static TextView txt_drr;

    private static String custAddr;
    private static Double custLon;
    private static Double custLat;
    private static String actualAddr;
    private static Double actualLon;
    private static Double actualLat;
    private static ImageView img_back;

    private static AMapLocationClient mLocationClient = null;
    private AMapLocationListener mLocationListener = null;
    private AMapLocationClientOption mLocationOption = null;

    private String title = "";
    private TextView tvTitle;


    private ImageView image_add_approver;
    private CircleImageView ivHanderIcon;
  /*  private GooutDatePickerDialog startDatePickerDialog;
    private GooutDatePickerDialog endDatePickerDialog;*/

    private long count;
    private String startPart;//上午or下午
    private String endPart;//上午or下午

    private String startDate;
    private String endDate;

    private long startTime = 0;
    private long endTime = 0;
    private long dayCount = 0;


    private TextView choose_approver;

    private AddressBookInfo approver;
    private PoiItem poiItem;

    private int userId;
    private String lat;
    private String lon;

    //时间选择器
    private TimePickerView pvTime;
    private boolean isStartTime = true;
    private SimpleDateFormat sdf = null;
    private SimpleDateFormat sdf2 = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_business_trip);
        if (getIntent().getExtras().containsKey("title")) {
            title = getIntent().getStringExtra("title");
        }


        mLocationClient = new AMapLocationClient(getApplicationContext());

        mLocationOption = new AMapLocationClientOption();
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(false);
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位

        mLocationListener = new AMapLocationListener() {
            @Override
            public void onLocationChanged(final AMapLocation aMapLocation) {
                if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
                    txt_drr.post(new Runnable() {
                        @Override
                        public void run() {
                            txt_drr.setText(aMapLocation.getAddress());
                            lat = String.valueOf(aMapLocation.getLatitude());
                            lon = String.valueOf(aMapLocation.getLongitude());
//                            custLat = aMapLocation.getLatitude();
//                            custLon = aMapLocation.getLongitude();
                            custAddr = aMapLocation.getAddress();
                            actualAddr = aMapLocation.getAddress();
                            actualLon = aMapLocation.getLongitude();
                            actualLat = aMapLocation.getLatitude();

                        }
                    });

                    mLocationClient.stopLocation();
                } else {

                }
            }
        };
        mLocationClient.setLocationListener(mLocationListener);
        mLocationClient.startLocation();

        intiView();

        //注册EventBus
        EventBus.getDefault().register(this);
        ScreenUtil.GetInfo(this);

    }

    //接收用EventBus传递的数据
    @Subscribe(threadMode = ThreadMode.MainThread)
    public void helloEventBus(MessageEvent message) {
        txt_drr.setText(message.getVaddress());
        lat = message.getLat();
        lon = message.getLon();
        Log.e("lon+1111", lon);
        Log.e("lat+1111", lat);
    }

    /**
     * 初始化控件
     */
    private void intiView() {
        tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTitle.setText(title);
        txt_date = (TextView) findViewById(R.id.txt_date);
        end_time_out = (TextView) findViewById(R.id.end_time_out);
        tvJob = (TextView) findViewById(R.id.tvJob);
        ivHanderIcon = (CircleImageView) findViewById(R.id.ivHanderIcon);

        tvName = (TextView) findViewById(R.id.tvName);
        img_back = (ImageView) findViewById(R.id.img_back);
        txt_record = (TextView) findViewById(R.id.txt_record);
        btn_ok = (Button) findViewById(R.id.btn_ok);
        lin_mapview = (LinearLayout) findViewById(R.id.lin_mapview);
        et_reason = (EditText) findViewById(R.id.et_reason);
        et_name = (EditText) findViewById(R.id.et_name);
        txt_drr = (TextView) findViewById(R.id.txt_drr);

        ll = (LinearLayout) findViewById(R.id.ll);

        //监听控件
        lin_mapview.setOnClickListener(this);
        btn_ok.setOnClickListener(this);
        btn_ok.setClickable(false);
        txt_record.setOnClickListener(this);
        img_back.setOnClickListener(this);


        choose_approver = (TextView) findViewById(R.id.choose_approver);

        image_add_approver = (ImageView) findViewById(R.id.image_add_approver);
        txt_date.setOnClickListener(this);
        end_time_out.setOnClickListener(this);

        et_name.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                if (s.length() > 0 && et_reason.getText().length() > 0) {
                    btn_ok.setBackgroundResource(R.drawable.renbao_btn_bg);
                    btn_ok.setClickable(true);
                } else {
                    btn_ok.setBackgroundResource(R.drawable.btn_on);
                    btn_ok.setClickable(false);
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        et_reason.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                if (s.length() > 0 && et_name.getText().length() > 0) {
                    btn_ok.setBackgroundResource(R.drawable.renbao_btn_bg);
                    btn_ok.setClickable(true);
                } else {
                    btn_ok.setBackgroundResource(R.drawable.btn_on);
                    btn_ok.setClickable(false);
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        //时间选择器初始化及配置
        pvTime = new TimePickerView(this, TimePickerView.Type.SHX);
        Calendar calendar = Calendar.getInstance();
        pvTime.setRange(calendar.get(Calendar.YEAR) - 10,
                calendar.get(Calendar.YEAR) + 45);
        pvTime.setCyclic(false);
        pvTime.setCancelable(true);
        sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
        sdf2 = new SimpleDateFormat("yyyy年MM月dd日");
        pvTime.setOnTimeSelectListener(this);
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.img_back) {
            finish();

        } else if (i == R.id.txt_record) {//查看签到记录
            //二期新需求，要显示我的外勤，我收到的外勤
            startActivity(new Intent(BusinessTripActivity.this, ApplyForBusinessTripActivity.class));
        } else if (i == R.id.btn_ok) {//确定签到
            // FieldAttendanceAction fa = new FieldAttendanceAction();
            if (et_name.getText().toString().trim().length() > 20) {
                Util.showToast(BusinessTripActivity.this, "客户名称不能超过20字");
                return;
            }
            if (et_reason.getText().toString().trim().length() > 50) {
                Util.showToast(BusinessTripActivity.this, "拜访缘由不能超过50字");
                return;
            }
            if (TextUtils.isEmpty(txt_date.getText().toString().trim())) {
                Util.showToast(BusinessTripActivity.this, "请输入拜访客户的开始日期");
                return;
            }
            if (TextUtils.isEmpty(end_time_out.getText().toString().trim())) {
                Util.showToast(BusinessTripActivity.this, "请输入拜访客户的结束日期");
                return;
            }

            if (TextUtils.isEmpty(et_name.getText().toString().trim())) {
                Util.showToast(BusinessTripActivity.this, "请输入拜访客户名称");
                return;
            }
            if (TextUtils.isEmpty(et_reason.getText().toString().trim())) {
                Util.showToast(BusinessTripActivity.this, "请输入拜访缘由");
                return;
            }
            if ("姓名".equals(tvName.getText().toString().trim())) {
                Util.showToast(BusinessTripActivity.this, "请选择审批人");
                return;
            }

            JsonBean jsonBean = new JsonBean();
//            SimpleDateFormat format =   new SimpleDateFormat( "yyyy-MM-dd" );
//
//            String time=txt_date.getText().toString();
//            String time1=end_time_out.getText().toString();
//
//            Date date = null;
//            Date date1 = null;
//            try {
//                date = format.parse(time);
//                date1=format.parse(time1);
//                jsonBean.setBeginVisitTime(String.valueOf(date.getTime()));
            jsonBean.setBeginVisitTime(String.valueOf(startTime));

//                jsonBean.setEndVisitTime(String.valueOf(date1.getTime()));
            jsonBean.setEndVisitTime(String.valueOf(endTime));
//
//            } catch (ParseException e) {
//                e.printStackTrace();
//            }

            jsonBean.setCustName(et_name.getText().toString());
            jsonBean.setCustAddr(txt_drr.getText().toString());
            jsonBean.setVisitCause(et_reason.getText().toString());
            jsonBean.setCustLat(lat);
            jsonBean.setCustLon(lon);
            jsonBean.setOutsideDay(count);
            Log.e("json", jsonBean.toJson());

            HttpClient.getInstance(this).post(new AddWorkOutsideInfo(userId, tvName.getText().toString(), jsonBean.toJson()), this);

            btn_ok.setClickable(false);

        } else if (i == R.id.lin_mapview) {//跳转到高德地图
            Intent intent = new Intent(BusinessTripActivity.this, VisitViewMapActivity.class);
            startActivity(intent);

        } else if (i == R.id.txt_date) {//开始日期
            isStartTime = true;
            pvTime.setTime(null);
            pvTime.show();
        } else if (i == R.id.end_time_out) {
            isStartTime = false;
            pvTime.setTime(null);
            pvTime.show();
        }
    }

    public void on(View view) {
        Intent intent = new Intent(this, ApproverActivity.class);
        intent.putExtra("isOrganiser", true);
        startActivityForResult(intent, 0);
    }


    //延迟2s在跳转
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                SystemClock.sleep(2000);//延时两秒执行finish
                finish();
            }
        }
    };

    private void getDayCount() {
        if (!TextUtils.isEmpty(startDate) && !TextUtils.isEmpty(endDate)) {
            long start = DateUtil.StringToDate(startDate, 7).getTime();
            long end = DateUtil.StringToDate(endDate, 7).getTime();
            if (start > end) {
                dayCount = -1;
                return;
            }
            count = (end - start) / (24 * 60 * 60 * 1000);
            if ("上午".equals(startPart)) count += 0.5;
            if ("下午".equals(endPart)) count += 0.5;
            dayCount = count;
        }
    }

    @Override
    public void onRequestStart(String tag) {

    }

    @Override
    public void onResponseSuccess(BaseResponse<?> response, String tag) {
        String value = response.getReturnObject().toString();
        Util.showToast(this, value);
//        btn_ok.setClickable(true);
        Toast.makeText(BusinessTripActivity.this, "因公外出申请成功", Toast.LENGTH_SHORT).show();
        Message msg = new Message();
        msg.what = 1;
        mHandler.sendMessage(msg);
    }

    @Override
    public void onResponseFail(String tag, int resultCode) {
        Util.showToast(this, "加载失败，请重试");
        btn_ok.setClickable(true);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {//resultCode为回传的标记
            case 1011:
                // TODO
                approver = (com.ciko.code.logic.bean.AddressBookInfo) data.getSerializableExtra("Approver");
                if (null != approver) {
                    userId = Integer.parseInt(approver.getUserId());
                    //设置职务
                    tvJob.setText(EmployeeEnum.typeOfValue(approver.getUserPositionMark()));
                    tvName.setText(approver.getContactName());
                    if (!TextUtils.isEmpty(approver.getUserHead())) {
                        Picasso.with(this).load(approver.getUserHead()).into(ivHanderIcon);
                    } else {
                        Picasso.with(this).load(R.drawable.chat_head_img).into(ivHanderIcon);
                    }
                    ll.setVisibility(View.VISIBLE);
                    image_add_approver.setVisibility(View.GONE);
                }
                break;
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mLocationClient != null) mLocationClient.stopLocation();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //注销EventBus
        EventBus.getDefault().unregister(this);
        if (mLocationClient != null) mLocationClient.onDestroy();

    }

    @Override
    public void onTimeSelect(String time) {
//2016年11月16日 上午
        if (isStartTime) {
            try {
                long startTempTime = 0;
                startPart = time.substring(time.lastIndexOf(" ") + 1, time.length());
                String curDate = "";
                String curTempDate = time.substring(0, time.lastIndexOf(" "));
                if ("上午".equals(startPart)) {
                    startTempTime = sdf2.parse(curTempDate).getTime();
                    curTempDate = curTempDate + " " + "09:00";
                    if (endTime != 0 && endTime < startTempTime) {
                        Toast.makeText(BusinessTripActivity.this, "结束时间要晚于开始时间", Toast.LENGTH_SHORT).show();
                        return;
                    } else {
                        startDate = curTempDate.substring(0, time.lastIndexOf(" "));
                        curDate = startDate + " " + "09:00";
                        startTime = sdf.parse(curDate).getTime();
                    }
                } else {
                    startTempTime = sdf2.parse(curTempDate).getTime();
                    curTempDate = curTempDate + " " + "18:00";
                    if (endTime != 0 && endTime < startTempTime) {
                        Toast.makeText(BusinessTripActivity.this, "结束时间要晚于开始时间", Toast.LENGTH_SHORT).show();
                        return;
                    } else {
                        startDate = curTempDate.substring(0, time.lastIndexOf(" "));
                        curDate = startDate + " " + "18:00";
                        startTime = sdf.parse(curDate).getTime();
                    }
                }
                getDayCount();
                if (0 == endTime) {
                    txt_date.setText(time);
                    txt_date.setTextColor(Color.BLACK);
                } else {
                    if (endTime - startTime >= 0) {
                        txt_date.setText(time);
                        txt_date.setTextColor(Color.BLACK);
                    } else {
                        Toast.makeText(BusinessTripActivity.this, "结束时间要晚于开始时间", Toast.LENGTH_SHORT).show();
                    }
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        } else {
            endPart = time.substring(time.lastIndexOf(" ") + 1, time.length());
            endDate = time.substring(0, time.lastIndexOf(" "));
            String curDate;
            if ("上午".equals(endPart)) {
                curDate = endDate + " " + "09:00";
            } else {
                curDate = endDate + " " + "18:00";
            }
            try {
                endTime = sdf.parse(curDate).getTime();
                getDayCount();
                if (0 == startTime) {
                    end_time_out.setText(time);
                    end_time_out.setTextColor(Color.BLACK);
                } else {
                    if (endTime - startTime >= 0) {
                        end_time_out.setText(time);
                        end_time_out.setTextColor(Color.BLACK);
                    } else {
                        Toast.makeText(BusinessTripActivity.this, "结束时间要晚于开始时间", Toast.LENGTH_SHORT).show();
                    }
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onBackPressed() {
        if (pvTime.isShowing()) {
            pvTime.dismiss();
        } else {
            BusinessTripActivity.this.finish();
        }
    }

    public class JsonBean {
        private String custName;
        private String custAddr;
        private String visitCause;
        private String custLon;
        private String custLat;
        private String beginVisitTime;
        private String endVisitTime;
        private double outsideDay;

        public double getOutsideDay() {
            return outsideDay;
        }

        public void setOutsideDay(double outsideDay) {
            this.outsideDay = outsideDay;
        }

        public String getCustName() {
            return custName;
        }

        public void setCustName(String custName) {
            this.custName = custName;
        }

        public String getCustAddr() {
            return custAddr;
        }

        public void setCustAddr(String custAddr) {
            this.custAddr = custAddr;
        }

        public String getVisitCause() {
            return visitCause;
        }

        public void setVisitCause(String visitCause) {
            this.visitCause = visitCause;
        }

        public String getCustLon() {
            return custLon;
        }

        public void setCustLon(String custLon) {
            this.custLon = custLon;
        }

        public String getCustLat() {
            return custLat;
        }

        public void setCustLat(String custLat) {
            this.custLat = custLat;
        }

        public String getBeginVisitTime() {
            return beginVisitTime;
        }

        public void setBeginVisitTime(String beginVisitTime) {
            this.beginVisitTime = beginVisitTime;
        }

        public String getEndVisitTime() {
            return endVisitTime;
        }


        public void setEndVisitTime(String endVisitTime) {
            this.endVisitTime = endVisitTime;
        }

        public String toJson() {
            Gson gson = new Gson();
            return gson.toJson(this);
        }
    }
}
